package com.example.shiyan2;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Timer;
import java.util.TimerTask;

public class Activity3 extends AppCompatActivity {

    private final ImageView[] imageViews = new ImageView[5];
    private final int[] imageResources = {R.drawable.first, R.drawable.second, R.drawable.third, R.drawable.fourth, R.drawable.fift};
    private int currentImageIndex = 0;
    private Timer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_3);

        // 初始化 ImageView 数组
        imageViews[0] = findViewById(R.id.imageView3);
        imageViews[1] = findViewById(R.id.imageView4);
        imageViews[2] = findViewById(R.id.imageView5);
        imageViews[3] = findViewById(R.id.imageView6);
        imageViews[4] = findViewById(R.id.imageView7);

        // 初始化返回按钮
        Button backButton = findViewById(R.id.button14);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 返回上一个活动
                onBackPressed();
            }
        });

        // 启动定时器
        startTimer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 销毁定时器
        stopTimer();
    }

    private void startTimer() {
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    // 隐藏所有 ImageView
                    for (ImageView imageView : imageViews) {
                        imageView.setVisibility(ImageView.INVISIBLE);
                    }

                    // 显示当前 ImageView
                    imageViews[currentImageIndex].setVisibility(ImageView.VISIBLE);
                    imageViews[currentImageIndex].setImageResource(imageResources[currentImageIndex]);

                    // 更新当前图片索引
                    currentImageIndex = (currentImageIndex + 1) % imageViews.length;
                });
            }
        }, 0, 1000); // 每隔 2 秒钟切换一次图片
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}